package com.chenyaowei.order.service.impl;

import com.chenyaowei.common.utils.DateUtils;
import com.chenyaowei.common.utils.StringUtils;
import com.chenyaowei.member.domain.CywMemberStatisticsInfo;
import com.chenyaowei.member.service.ICywMemberStatisticsInfoService;
import com.chenyaowei.order.request.StatisticsRequest;
import com.chenyaowei.order.service.ICywOrderService;
import com.chenyaowei.order.service.ICywStatisticsService;
import com.chenyaowei.order.vo.StatisticsVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.Year;
import java.util.Date;
import java.util.List;

@Service
public class CywStatisticsServiceImpl implements ICywStatisticsService {

    @Autowired
    private ICywOrderService orderService;

    @Autowired
    private ICywMemberStatisticsInfoService memberStatisticsInfoService;

    @Override
    public StatisticsVO statistics(StatisticsRequest statisticsRequest) {
        StatisticsVO statisticsVO = new StatisticsVO();
        List<CywMemberStatisticsInfo> memberStatisticsInfoList = memberStatisticsInfoService.selectCywMemberStatisticsInfoList(null);
        //总营业额
        BigDecimal todayTurnover = memberStatisticsInfoList.stream().map(CywMemberStatisticsInfo::getConsumeAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
        statisticsVO.setTotalTurnover(todayTurnover);
        //总会员数
        statisticsVO.setTodayMemberCount(memberStatisticsInfoList.size());
        //总订单数
        Integer totalOrderCount = memberStatisticsInfoList.stream().map(CywMemberStatisticsInfo::getOrderCount).reduce(0, Integer::sum);
        statisticsVO.setTotalOrderCount(totalOrderCount);
        //今日营业额
        LocalDate now = LocalDate.now();

        statisticsVO.setTodayTurnover(orderService.totalTurnoverSum(DateUtils.toDate(now.atStartOfDay()), DateUtils.toDate(now.atTime(23, 59, 59))));
        //年度每月营业额
        String year = statisticsRequest.getYear();
        Date yearStart = DateUtils.toDate(getYearStart(StringUtils.isEmpty(year) ? null : year));
        Date yearEnd = DateUtils.toDate(getYearEnd(StringUtils.isEmpty(year) ? null : year));
        statisticsVO.setMonthTurnovers(orderService.monthTurnoverSum(yearStart, yearEnd));
        return statisticsVO;
    }

    private LocalDate getYearStart(String yearString) {
        Year year;
        if (yearString == null || yearString.isEmpty()) {
            year = Year.now();
        } else {
            year = Year.of(Integer.parseInt(yearString));
        }
        return year.atDay(1);
    }

    private LocalDate getYearEnd(String yearString) {
        Year year;
        if (yearString == null || yearString.isEmpty()) {
            year = Year.now();
        } else {
            year = Year.of(Integer.parseInt(yearString));
        }
        return year.atDay(Year.isLeap(year.getValue()) ? 366 : 365);
    }
}
